Jquery / Forms / Form Validation using jquery validation plugin
Form Validation using plugin
-
STEPS
Plugin
1. Form
2. Script
1. Definde function
$('form[id="second_form"]').validate({ }); second_form is id of form 2. Write rules for mandatory fields
$('form[id="second_form"]').validate({ rules: { fname: 'required', lname: 'required', user_email: { required: true, email: true, }, psword: { required: true, minlength: 8, } } }); We use the name of fields inside rules parameter 3. Write message for mandatory fields
$('form[id="second_form"]').validate({ messages: { fname: 'This field is required', lname: 'This field is required', user_email: 'Enter a valid email', psword: { minlength: 'Password must be at least 8 characters long' } }, }); We use the name of fields inside messages parameter 4. Write form submit
$('form[id="second_form"]').validate({ submitHandler: function(form) { form.submit(); } }); Form submit() is used inside submitHandler parameter 3. Completed code
$('form[id="second_form"]').validate({ rules: { fname: 'required', lname: 'required', user_email: { required: true, email: true, }, psword: { required: true, minlength: 8, } }, messages: { fname: 'This field is required', lname: 'This field is required', user_email: 'Enter a valid email', psword: { minlength: 'Password must be at least 8 characters long' } }, submitHandler: function(form) { form.submit(); } }); 4. Another example
$("#signupForm").validate({ // In 'rules' user have to specify all the // constraints for respective fields rules: { firstname: "required", lastname: "required", username: { required: true, minlength: 2 // For length of lastname }, password: { required: true, minlength: 5 }, confirm_password: { required: true, minlength: 5, // For checking both passwords are same or not equalTo: "#password" }, email: { required: true, email: true }, agree: "required" }, // In 'messages' user have to specify message as per rules messages: { firstname: " Please enter your firstname", lastname: " Please enter your lastname", username: { required: " Please enter a username", minlength: " Your username must consist of at least 2 characters" }, password: { required: " Please enter a password", minlength: " Your password must be consist of at least 5 characters" }, confirm_password: { required: " Please enter a password", minlength: " Your password must be consist of at least 5 characters", equalTo: " Please enter the same password as above" }, agree: "Please accept our policy" } }); });